﻿/*
 DotNetNuke - http://www.dotnetnuke.com
 Copyright (c) 2002-2010 by DotNetNuke Corp.

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.

*/
using System;
using System.Collections;
using System.Data;

using System.Runtime.InteropServices;
using System.Web;
using System.Web.UI.WebControls;
using System.Xml;

using DotNetNuke.Common;
using DotNetNuke.Entities.Users;
using DotNetNuke.Services.Tokens;

namespace DotNetNuke.Modules.UserDefinedTable
{


  public class DataTypeLookUp : DataType
  {




    [StructLayout(LayoutKind.Sequential)]
    private struct FieldSetting
    {
      public string Title;
      public string sourceColumn;
      public string sourceType;
      public string tokenText;
    }




    private string GetTypeName(DataTable FieldsTable, string ColumnName)
    {
      using (DataView view = new DataView(FieldsTable, string.Format("{0}='{1}'", FieldsTableColumn.Title, ColumnName), "", DataViewRowState.CurrentRows))
      {
        return Utilities.CStrN((view[0][FieldsTableColumn.Type]), "");
      }
    }

    public override void RenderValuesToHtmlInsideDataSet(DataSet ds, int ModuleId, bool noScript)
    {
      IEnumerator enumerator = null;
      IEnumerator enumerator2 = null;
      ArrayList list = new ArrayList();
      try
      {
        enumerator = ds.Tables[DataSetTableName.Fields].Rows.GetEnumerator();
        while (enumerator.MoveNext())
        {
          DataRow current = (DataRow)enumerator.Current;
          if ((string)current[FieldsTableColumn.Type] == this.Name)
          {
            FieldSetting setting = new FieldSetting();
            setting.Title = (string)current[FieldsTableColumn.Title];
            setting.sourceColumn = Utilities.CStrN((current[FieldsTableColumn.InputSettings]), "");
            if (!string.IsNullOrEmpty(setting.sourceColumn))
            {
              setting.tokenText = Utilities.CStrN((current[FieldsTableColumn.Default]), "");
              setting.sourceType = this.GetTypeName(ds.Tables[DataSetTableName.Fields], setting.sourceColumn);
              list.Add(setting);
              current[FieldsTableColumn.ValueColumn] = XmlConvert.EncodeName(setting.Title);
            }
          }
        }
      }
      finally
      {
        if (enumerator is IDisposable)
          (enumerator as IDisposable).Dispose();

      }
      try
      {
        enumerator2 = ds.Tables[DataSetTableName.Data].Rows.GetEnumerator();
        while (enumerator2.MoveNext())
        {
          IEnumerator enumerator3 = null;
          DataRow row = (DataRow)enumerator2.Current;
          try
          {
            enumerator3 = list.GetEnumerator();
            while (enumerator3.MoveNext())
            {
              FieldSetting setting2 = (FieldSetting)enumerator3.Current;
              row[setting2.Title] = new TokenReplace(ModuleId).GetValue(setting2.tokenText, row, setting2.sourceColumn, setting2.sourceType);
            }
            continue;
          }
          finally
          {
            if (enumerator3 is IDisposable)
              (enumerator3 as IDisposable).Dispose();

          }
        }
      }
      finally
      {
        if (enumerator2 is IDisposable)
          (enumerator2 as IDisposable).Dispose();

      }
    }





    public override void SetStylesAndFormats(BoundField Column, string Format)
    {
      base.SetStylesAndFormats(Column, Format);

      if ( !string.IsNullOrEmpty(Format) )
      {
        Column.DataFormatString = string.Format("{{0:{0}}}", Format);
      }
    }





    public override bool InputSettingsIsValueList
    { get { return false; } }




    public override string Name
    { get { return "LookUp"; } }




    public override bool SupportsDefaultValue
    { get { return true; } }




    public override bool SupportsHideOnEdit
    { get { return true; } }




    public override bool SupportsInputSettings
    { get { return true; } }




    public override bool SupportsOutputSettings
    { get { return false; } }




    public override bool SupportsSearch
    { get { return true; } }





    private class TokenReplace : BaseCustomTokenReplace
    {
      private int ModuleId;

      public TokenReplace(int moduleId)
      {
        if (HttpContext.Current != null)
        {
          this.AccessingUser = (UserInfo)System.Web.HttpContext.Current.Items["UserInfo"];
        }
        else
        {
          this.AccessingUser = new UserInfo();
        }
        this.CurrentAccessLevel = Scope.DefaultSettings;
        this.ModuleId = moduleId;
      }





      public string GetValue(string tokenText, DataRow row, string sourceColumn, string sourceType)
      {
        base.PropertySource.Clear();
        switch (sourceType.ToLowerInvariant())
        {
          case "createdby":
          case "changedby":
          case "userlink":
            {
              UserInfo user = ((IUserSource)DataType.ByName(sourceType)).GetUser(sourceColumn, row);
              if (user == null)
              {
                return "";
              }
              base.PropertySource["user"] = user;
              base.PropertySource["profile"] = new ProfilePropertyAccess(user);
              break;
            }
          case "download":
          case "url":
          case "image":
            {
              string id = Utilities.CStrN((row[sourceColumn + DataTableColumn.Appendix_Original]), "");
              if ( !string.IsNullOrEmpty(id) )
                base.PropertySource["file"] = new DownloadPropertyAccess(id, Globals.GetPortalSettings().PortalId, this.ModuleId);
              
              break;
            }
          default:
            if (DataType.ByName(sourceType) is IEmailAdressSource)
            {
              string emailAddress = ((IEmailAdressSource)DataType.ByName(sourceType)).GetEmailAddress(sourceColumn, row);

              if (!string.IsNullOrEmpty(emailAddress))
                base.PropertySource["gravatar"] = new GravatarPropertyAccess(emailAddress);
              
            }
            else
            {
              return "";
            }
            break;
        }
        return this.ReplaceTokens(tokenText);
      }
    }


  }

}

